package com.zone.core.base

import android.os.Bundle
import android.view.LayoutInflater
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelLazy
import androidx.lifecycle.ViewModelProvider
import com.zone.core.BR
import com.zone.core.contract.OnEventListener
import com.zone.core.ext.bind
import com.zone.core.model.EVENT_BACK
import javax.inject.Inject

/**
 *Author: last
 *Time: 2023-11-04
 *Description: xxx
 */
abstract class BaseBindingViewModelActivity<BINDING : ViewDataBinding, VM : BaseViewModel> :
    BaseBindingActivity<BINDING>(), OnEventListener {

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    val viewModel: VM by lazy {
        createViewModel()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        inject()
        super.onCreate(savedInstanceState)
    }

    private fun createViewModel(): VM {
        val viewModel = getViewModelType(javaClass)?.let {
            ViewModelProvider(this, viewModelFactory)[it] as VM
        }
        viewModel?.bind(this)
        return viewModel!!
    }

    override fun initDataBinding(binding: BINDING) {
        binding.setVariable(BR.vm, viewModel)
    }

    abstract fun inject()

    override fun onEvent(eventId: Int) {
        if (eventId == EVENT_BACK) {
            finish()
        }
    }

    inline fun <reified VB : ViewDataBinding> bindLayout(crossinline inflater: (LayoutInflater) -> VB) {
        inflater(layoutInflater)
    }

    inline fun <reified VM : ViewModel> viewModes(noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null): Lazy<VM> {
        val factoryPromise = factoryProducer ?: {
            defaultViewModelProviderFactory
        }
        return ViewModelLazy(VM::class, { viewModelStore }, factoryPromise)
    }
}